package cn.lixin.org.controller;

import cn.lixin.basic.utils.AjaxResult;
import cn.lixin.basic.utils.PageList;
import cn.lixin.org.domain.Employee;
import cn.lixin.org.query.EmployeeQuery;
import cn.lixin.org.service.IEmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController //@Controller+@ResponseBody(转换json)
@RequestMapping("/employee")
@Api(tags = "员工接口",description = "员工接口详细描述")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    @ApiOperation(value = "查询所有",notes = "查询所有员工")
    public List<Employee> queryAll(){
        return employeeService.loadAll();
    }

    /**
     * 根据id查询员工
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个员工",notes = "根据id查询员工")
    public Employee queryById(@PathVariable("id") Long id){ // PathVariable：一个{}的时候可以不写
        return employeeService.loadById(id);
    }

    /**
     * 高级查询
     * @return
     * RequestBody: 如果请求的是一个对象，则用RequestBody ，请求体
     *  axios get不支持传对象
     */
    @PostMapping
    @ApiOperation(value = "高级查询",notes = "根据query高级查询")
    public PageList<Employee> pageList(@RequestBody EmployeeQuery query){ // PathVariable：一个{}的时候可以不写
        System.out.println( employeeService.queryPage(query));
        return employeeService.queryPage(query);
    }

    /**
     * 修改添加
     * PutMapping: 修改或添加
     * @param employee
     * @return
     */
    @PutMapping
    @ApiOperation(value = "员工添加或修改",notes = "如果有id就是修改否则就是添加")
    public AjaxResult addOrUpdate(@RequestBody Employee employee){
        try {
            if (employee.getId() == null){
                employeeService.save(employee);
            }else {
                employeeService.update(employee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /**
     * 删除
     * DeleteMapping: 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除",notes = "如果有id就是修改否则就是添加")
    public AjaxResult del(@PathVariable("id") Long id){
        try {
           employeeService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }



}
